package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.List;
import java.util.Map;

/**
 * @author 江南大学1033190417
 * @date 2022/5/19 14:59
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //一行一行读
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new GuliException(20001, "文件数据为空");
        }
        String oneSubject = subjectData.getOneSubject();
        String twoSubject = subjectData.getTwoSubject();
        //添加一级分类
        EduSubject subject = this.existOneSubject(oneSubject);
        if (subject == null) {//没有相同的一级分类
            subject = new EduSubject();
            subject.setParentId("0").setTitle(oneSubject);
            subjectService.save(subject);
        }
        //添加二级分类
        EduSubject existTwoSubject = this.existTwoSubject(twoSubject, subject.getId());
        if (existTwoSubject == null) {
            existTwoSubject = new EduSubject();
            existTwoSubject.setTitle(twoSubject).setParentId(subject.getId());
            subjectService.save(existTwoSubject);
        }
    }

    //判断一级分类不能重复
    public EduSubject existOneSubject(String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name).eq("parent_id", 0);
        return subjectService.getOne(wrapper);
    }

    //判断二级分类
    public EduSubject existTwoSubject(String name, String parentId) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name).eq("parent_id", parentId);
        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        super.invokeHeadMap(headMap, context);
    }
}
